package com.zyddd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zyddd.common.R;
import com.zyddd.dto.UserDto;
import com.zyddd.pojo.User;
import com.zyddd.service.*;
import com.zyddd.utils.EmailUtil;
import com.zyddd.utils.RandomCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.stream.Collectors;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private DegreeService degreeService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private JobService jobService;
    @Autowired
    private ResearchFieldService researchFieldService;
    @Autowired
    private TitleService titleService;
    @Autowired
    private UserService userService;

    private Boolean isUsernameDuplicate(String username) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        return userService.getOne(queryWrapper) != null;
    }

    @Transactional
    @PostMapping("register")
    public R<String> register(@RequestBody UserDto userDto) {
        //判断用户名是否重复
        if (isUsernameDuplicate(userDto.getUser().getUsername())) {
            return R.error("用户名重复");
        }
        //密码加密
        userDto.getUser().setPassword(DigestUtils.md5DigestAsHex(userDto.getUser().getPassword().getBytes()));

        //user信息入库
        userService.save(userDto.getUser());

        //设置user_id为当前用户
        Integer userId = userDto.getUser().getId();
        userDto.setDegrees(userDto.getDegrees().stream().peek(it -> it.setUserId(userId)).collect(Collectors.toList()));
        userDto.setDepartments(userDto.getDepartments().stream().peek(it -> it.setUserId(userId)).collect(Collectors.toList()));
        userDto.setTitles(userDto.getTitles().stream().peek(it -> it.setUserId(userId)).collect(Collectors.toList()));
        userDto.setJobs(userDto.getJobs().stream().peek(it -> it.setUserId(userId)).collect(Collectors.toList()));
        userDto.setResearchFields(userDto.getResearchFields().stream().peek(it -> it.setUserId(userId)).collect(Collectors.toList()));

        //其他信息入库
        degreeService.saveBatch(userDto.getDegrees());
        departmentService.saveBatch(userDto.getDepartments());
        titleService.saveBatch(userDto.getTitles());
        jobService.saveBatch(userDto.getJobs());
        researchFieldService.saveBatch(userDto.getResearchFields());

        return R.success("注册成功");
    }


}
